/*
 * @Description: 
 * @Autor: 商晓彬
 * @Date: 2021-08-24 10:14:40
 * @LastEditors: 商晓彬
 * @LastEditTime: 2021-12-29 10:45:35
 */
import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Input, Output, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { MessageService } from '@abp/message/message.service';
import { StorePutServiceProxy, StoreFunctionsServiceProxy, StoreDropListOutDto } from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Table } from 'primeng/components/table/table';
@Component({
    selector: 'app-batch-warehousing',
    templateUrl: './batch-warehousing.component.html',
    styleUrls: ['./batch-warehousing.component.less']
})
export class BatchWarehousingComponent extends AppComponentBase {
    @ViewChild('dataTable') dataTable: Table;
    //引入子组件
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Input() warehouseData: any;  //仓库信息
    @Input() title: string;  //标题
    qualifiedNumber = undefined;
    saving = false;
    active = false;
    code = undefined;
    inputs = [];
    time = undefined;
    modelOptions = [];
    unitOptions = [];
    sendTimeOptions = [];
    materialsNodeOptions = [];
    moduleOptions = [];
    binLocationOptions = [];
    materialCategoryOptions = [];
    //日期显示中文
    chinese = {
        /** 每周第一天，0代表周日 */
        firstDayOfWeek: 0,
        /** 每周天数正常样式 */
        dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        /** 每周天数短样式（位置较小时显示） */
        dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
        /** 每周天数最小样式 */
        dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
        /** 每月月份正常样式 */
        monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
        /** 每月月份短样式 */
        monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
    }
    materialsPropertyOptions = [
        {
            label: '正常品',
            value: 0
        }, {
            label: '返修品',
            value: 1
        }
    ];
    saveFlag = true;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _storePutServiceProxy: StorePutServiceProxy,
        private _storeFunctionsServiceProxy: StoreFunctionsServiceProxy,
    ) {
        super(injector);
    }
    getQuantity(msg, index) {
    }
    ngOnInit() {
        //单位
        this._storeFunctionsServiceProxy.getCodeDropList(
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.unitOptions = [];
                this.unitOptions = result;
            });
        //型号（产品代号）
        this._storeFunctionsServiceProxy.getRocketModeDropList(
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.modelOptions = [];
                this.modelOptions = result;
            });
        //物料类别
        this._storeFunctionsServiceProxy.getMaterialsTypeDropList(
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.materialsNodeOptions = [];
                this.materialsNodeOptions = result;
            });
        //储位
        this._storeFunctionsServiceProxy.getBinLocationDropList(
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                this.binLocationOptions = [];
                this.binLocationOptions = result;
            });
    }
    getSendTime(event, record) {
        //发次
        this._storeFunctionsServiceProxy.getRocketLotNoDropList(
            record.models
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                record.sendTimeOptions = [];
                record.sendTimeOptions = result;
            });
    }
    search() {
        this._storePutServiceProxy.getCertificateInfoByCerCode(this.qualifiedNumber)
            .pipe(finalize(() => { }))
            .subscribe(rs => {
                for (const item of this.inputs) {
                    if (rs.qualifiedNumber == item.qualifiedNumber) {
                        this._messageService.info('不能新增重复的合格证');
                        return;
                    }
                }
                let input = rs;
                if (rs.productCode != null) {
                    let model = rs.productCodeName.split(',');
                    let modelValue = rs.productCode.split(',');
                    let sendTime = [];
                    let sendTimeValue = [];
                    if (rs.sendTime != null) {
                         sendTime = rs.sendTimeName.split(',');
                         sendTimeValue = rs.sendTime.split(',');
                    }
                    //型号（产品代号）
                    this._storeFunctionsServiceProxy.getRocketModeDropList(
                    ).pipe(finalize(() => { }))
                        .subscribe(result => {
                            this.modelOptions = [];
                            this.modelOptions = result;
                            input.models = [];
                            for (let i = 0; i < model.length; i++) {
                                const item = model[i];
                                let data = new StoreDropListOutDto();
                                data.label = item;
                                data.value = modelValue[i];
                                input.models.push(data);
                            }
                            this._storeFunctionsServiceProxy.getRocketLotNoDropList(
                                input.models
                            ).pipe(finalize(() => { }))
                                .subscribe(result => {
                                    input.sendTimeOptions = [];
                                    input.sendTimeOptions = result;
                                    input.sendTimes = [];
                                    for (let i = 0; i < sendTime.length; i++) {
                                        const item = sendTime[i];
                                        let data = new StoreDropListOutDto();
                                        data.label = item;
                                        data.value = sendTimeValue[i];
                                        input.sendTimes.push(data);
                                    }
                                });
                        });

                };
                if (rs.materialCategoryId != null) {
                    this._storeFunctionsServiceProxy.getSegmentationMaterialsTypeDropList(
                        input.materialsNodeId
                    ).pipe(finalize(() => { }))
                        .subscribe(result => {
                            this.materialCategoryOptions = [];
                            this.materialCategoryOptions = result;
                            this._storeFunctionsServiceProxy.getSegmentationMaterialsTypeDropList(
                                input.materialsNodeId
                            ).pipe(finalize(() => { }))
                                .subscribe(result => {
                                    input.materialCategoryOptions = [];
                                    input.materialCategoryOptions = result;
                                    input.materialCategoryId = rs.materialCategoryId;
                                });
                        });
                }
                this.inputs.push(input);
            });
    }
    save() {
        let input = [];
        for (const iterator of this.inputs) {
            //如果选择仓库则赋值
            if (this.warehouseData != undefined) {
                iterator.storeId = this.warehouseData.value;
                iterator.stroeName = this.warehouseData.label;
            }
            if (iterator.models) {
                for (let i = 0; i < iterator.models.length; i++) {
                    let item = iterator.models[i];
                    if (i == 0 && iterator.models.length - 1 != 0) {
                        iterator.productCode = item.value + ',';
                    } else if (i == 0 && iterator.models.length - 1 == 0) {
                        iterator.productCode = item.value;
                    } else if (i == iterator.models.length - 1) {
                        iterator.productCode = iterator.productCode + item.value;
                    } else {
                        iterator.productCode = iterator.productCode + item.value + ',';
                    }
                }
            } else {
                this._messageService.error("请先选择型号")
            }
            if (iterator.sendTimes) {
                for (let i = 0; i < iterator.sendTimes.length; i++) {
                    let item = iterator.sendTimes[i];
                    if (i == 0 && iterator.sendTimes.length - 1 != 0) {
                        iterator.sendTime = item.value + ',';
                    } else if (i == 0 && iterator.sendTimes.length - 1 == 0) {
                        iterator.sendTime = item.value;
                    } else if (i == iterator.sendTimes.length - 1) {
                        iterator.sendTime = iterator.sendTime + item.value;
                    } else {
                        iterator.sendTime = iterator.sendTime + item.value + ',';
                    }
                }
            } else {
                this._messageService.error("请先选择发次")
            }

            for (const item of this.materialsNodeOptions) {
                if (item.value == iterator.materialsNodeId) {
                    iterator.materialsNode = item.label;
                }
            }
            for (const item of this.materialCategoryOptions) {
                if (item.value == iterator.materialCategoryId) {
                    iterator.materialCategory = item.label;
                }
            }
            for (const item of this.unitOptions) {
                if (item.value == iterator.unitId) {
                    iterator.unit = item.label;
                }
            }
            for (const item of this.binLocationOptions) {
                if (item.value == iterator.binLocationId) {
                    iterator.binLocation = item.label;
                }
            }
            iterator.warehousMethod = 0;//合格证入库
        }
        for (const iterator of this.inputs) {
            delete iterator.materialCategoryOptions
            input.push(iterator)
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._storePutServiceProxy.createStorePutContent(input, "B1D77AA5-2F06-4C12-86BE-E60CBB00F991")
                .pipe(finalize(() => { this.saving = false; }))
                .subscribe((rs) => {
                    this.saveFlag = true;
                    if (rs.code == 0) {
                        this._messageService.success('保存成功');
                        this.close();
                    } else {
                        this._messageService.error(rs.message);
                    }
                });
        }
    }
    //打开弹窗
    onShown(): void {
        this.active = true;
    }
    onChange(event, record) {
        //物料细类
        this._storeFunctionsServiceProxy.getSegmentationMaterialsTypeDropList(
            event.value
        ).pipe(finalize(() => { }))
            .subscribe(result => {
                record.materialCategoryOptions = [];
                record.materialCategoryOptions = result;
            });
    }
    //查看新增任务
    show(): void {
        this.active = true;
        this.modal.show();
    }
    initEditInfo() {

    }
    //关闭事件
    close(): void {
        //清空form表单 
        this.inputs = []
        this.qualifiedNumber = undefined;
        this.active = false;
        this.modalSave.emit();
        this.modal.hide();
    }
    tableDel(index) {
        this.inputs.splice(index, 1);
    }
}
